<template>
  <van-button
    :icon="isLike === 1 ? 'good-job' : 'good-job-o'"
    :style="{ color: isLike === 1 ? 'red' : '#777' }"
    :loading="isLoading"
    @click="likeFn"
  ></van-button>
</template>

<script>
import { addLike, deleteLike } from "@/api/article.js";
export default {
  data() {
    return {
      isLoading: false, //收藏状态
    };
  },
  model: {
    prop: "isLike",
    event: "updated-isLike",
  },
  props: {
    isLike: {
      type: Number,
      required: true,
    },
    artId: {
      type: [Number, String],
      required: true,
    },
  },
  methods: {
    async likeFn() {
      this.isLoading = true;
      try {
        let state = -1; //默认点赞状态是无状态
        if (this.isLike === 1) {
          // 已经点赞了执行取消点赞
          await deleteLike(this.artId);
        } else {
          // 没有点赞执行点赞
          await addLike(this.artId);
          state = 1; //点赞之后状态为1
        }
        this.$toast.success(state === 1 ? "点赞成功" : "取消点赞");
        this.$emit("updated-isLike", state);
      } catch (err) {
        let message = "操作失败请稍等重试";
        if (err.response && err.response.status) {
          switch (err.response.status) {
            case 400:
              message = "自己不能点赞自己";
              break;
            case 401:
              message = "用户未认证";
              break;
            case 507:
              message = "数据库错误";
              break;
          }
        }
        this.$toast.fail(message);
      }
      this.isLoading = false;
    },
  },
};
</script>

<style scoped>
</style>